<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12" style="margin: 0 0 10px 0">
        <el-button type="primary" :disabled="userIds.length <= 0" :loading="autoLoading" @click="permissionRole()"
          >取消授权</el-button
        >
      </el-col>
    </el-row>
    <div class="allocation-permission-layout">
      <div class="left-layout">
        <TablePro
          :columns="roleColumns"
          :data="roleData"
          :showPage="false"
          :showTools="false"
          v-loading="roleLoading"
          @row-click="rowClickHandler"
          row-key="roleId"
        />
      </div>
      <div class="right-layout">
        <TablePro
          :columns="userColumns"
          :data="userData"
          :showPage="false"
          :highlight-current-row="true"
          :showTools="false"
          v-loading="userLoading"
          row-key="userId"
          ref="tableRef"
          @selection-change="handleSelectionChange"
        />
      </div>

      <el-dialog v-model="dialogVisible" title="授权" width="800" :before-close="handleClose">
        <el-transfer
          :data="allRoleList"
          v-model="hasRoleList"
          :titles="['所有角色', '拥有角色']"
          :button-texts="['取消授权', '添加授权']"
          :props="{ label: 'roleName', key: 'roleId' }"
          @change="handleChange"
        />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="savaHasRole" :disabled="isDisabled">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="orgDialog" title="组织授权" width="800" :before-close="handleOrgClose" :destroy-on-close="true">
        <TablePro
          ref="orgTableRef"
          row-key="organizationId"
          :columns="orgColumns"
          :data="orgData"
          :showPage="false"
          :showTools="false"
          @selection-change="handleSelectionChange"
        />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="orgDialog = false">取消</el-button>
            <el-button type="primary" @click="savaHasOrgHandler" :loading="isSavaOrgLoading">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="tsx">
import type { TransferDirection, TransferKey } from "element-plus";
import type { TableProCloumn } from "@/typings";
import { allocatedListApi, roleListApi, authUserCancelAllApi, authUserAuthRoleApi } from "@/api";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import TablePro from "@/components/TablePro/TablePro.vue";

// 定义加载状态和对话框可见性
const userLoading = ref<boolean>(false);
const roleLoading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const orgDialog = ref<boolean>(false);
const router = useRouter();
const currentUserId = ref<string>("");
// const currentRole = ref<any>();
// const currentRoleOrg = ref<any[]>([]);
const allRoleList = ref<any[]>([]);
// const selectOrgIds = ref<string[]>([]);
const isDisabled = ref<boolean>(true);
const orgTableRef = ref();
const hasRoleList = ref<any[]>([]);
const userData = ref<any[]>([]);
const roleData = ref<any[]>([]);
const orgData = ref<any[]>([]);

// 用户列定义
const userColumns = ref<TableProCloumn[]>([
  {
    type: "selection",
    width: 50
  },
  {
    label: "用户编号",
    prop: "userId"
  },
  {
    label: "用户名称",
    prop: "userName"
  },
  {
    label: "操作",
    width: 180,
    fixed: "right",
    render: ({ row }) =>
      row.admin ? (
        ""
      ) : (
        <el-button type="primary" link onClick={() => permissionRole(row)}>
          取消授权
        </el-button>
      )
  }
]);

// 角色列定义
const roleColumns = ref<TableProCloumn[]>([
  {
    label: "角色ID",
    prop: "roleId"
  },
  {
    label: "角色名称",
    prop: "roleName"
  },
  {
    label: "生效日期",
    prop: "effectiveDate"
  },
  {
    label: "失效日期",
    prop: "expiringDate"
  },
  {
    label: "操作",
    width: 200,
    fixed: "right",
    render: ({ row }) => {
      return (
        <div>
          <el-button type="primary" link onClick={() => handleDistribution(row)}>
            分配权限
          </el-button>
        </div>
      );
    }
  }
]);

// 组织列定义
const orgColumns = ref<TableProCloumn[]>([
  {
    type: "selection",
    width: 60
  },
  {
    type: "index",
    label: "序号",
    width: 80
  },
  {
    label: "组织ID",
    prop: "organizationId"
  },
  {
    label: "组织名称",
    prop: "organizationName"
  }
]);

// 授权参数配置
const params: any = {
  userId: "",
  add: [],
  del: []
};
const isSavaOrgLoading = ref<boolean>(false);

// 组件挂载时初始化用户
onMounted(() => {
  initUser();
});

// 定义用户列表和分页
// const userList = ref<any[]>([]);
const total = ref<number>(0);
// const pageSize = ref<number>(10);
// const pageNum = ref<number>(1);
const queryParams = ref<any>({});

// 初始化用户
const initUser = async () => {
  try {
    const res = await roleListApi({ ...queryParams.value });
    if (res.code === 200) {
      roleData.value = res.data;
      total.value = res.total as number;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("Error fetching data", error);
  }
};

// 获取用户
const getUsers = async (roleId?: string) => {
  roleLoading.value = true;
  try {
    const result = await allocatedListApi(roleId as string);
    if (result.code === 200) {
      userData.value = result.data;
    }
  } catch (error) {
    console.error("Error fetching data");
  } finally {
    roleLoading.value = false;
  }
};

// 获取所有角色列表
// const getAllRole = async () => {};

// 用户授权
const autoLoading = ref<boolean>(false);
const permissionRole = async (row?: any) => {
  autoLoading.value = true;
  if (row) {
    userIds.value = [row.userId];
  }

  try {
    const result = await authUserCancelAllApi(currentUserId.value, userIds.value.join(","));
    if (result.code === 200) {
      autoLoading.value = false;
      ElMessage.success("取消授权成功");
      initUser();
      getUsers(currentUserId.value);
      userIds.value = [];
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error(error);
  }
};

// 处理分配权限
const handleDistribution = (row: any) => {
  router.push({ name: "systemRolePerssionRole", params: { roleId: row.roleId } });
};

// 点击角色列表获取用户列表
const rowClickHandler = (row: any) => {
  currentUserId.value = row.roleId;
  getUsers(row.roleId);
};

// 处理组织权限
// const handleOrgPermission = async (row: any) => {
//   orgDialog.value = true;
//   currentRole.value = row;
// };

// 保存角色授权
const savaHasRole = async () => {
  try {
    params.userId = currentUserId.value;
    const result = await authUserAuthRoleApi({ userId: currentUserId.value, roleIds: hasRoleList.value.join(",") });

    if (result.code === 200) {
      ElMessage.success("授权成功");
      initUser();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    ElMessage.error("授权失败，请稍后再试");
  } finally {
    params.add = [];
    params.del = [];
    dialogVisible.value = false;
  }
};

// 用户ID集合
const userIds = ref<string[]>([]);

// 处理选择变化
const handleSelectionChange = (data: any[]) => {
  userIds.value = data.map((item: any) => item.userId);
};

// 保存组织授权处理
const savaHasOrgHandler = async () => {};

// 处理角色转移
const handleChange = (value: TransferKey[], direction: TransferDirection, movedKeys: TransferKey[]) => {
  isDisabled.value = false;
  if (direction === "right") {
    params.add = movedKeys;
  }
  if (direction === "left") {
    params.del = movedKeys;
  }
};

// 处理对话框关闭
const handleClose = (done: () => void) => {
  done();
};

// 处理组织对话框关闭
const handleOrgClose = (done: () => void) => {
  done();
};
</script>

<style scoped lang="scss">
.allocation-permission-layout {
  width: 100%;
  height: 100%;
  display: flex;

  .left-layout,
  .right-layout {
    flex: 1;
  }

  .left-layout {
    margin-right: 10px;
  }
}
</style>
